/**
 * 基于键盘的扫描枪工具类
 *  var scanner = BarcodeScanner({
 *      el: document,
 *      success: function(barcode) {
 *          $('#product-list tr').each(function(i, el) {
 *              var $el = $(el), $countEl, count;
 *
 *              $el.removeClass("scan-item");
 *              if(barcode == $el.data('barcode')) {
 *                  $el.addClass("scan-item");
 *                  $countEl = $el.find('input:last');
 *                  count = parseInt($countEl.val()) || 0;
 *                  $countEl.val(count + 1);
 *              }
 *          });
 *      }
 *  });
 * scanner.resume();
 * TODO 状态区域
 */
(function ($, exports) {
    var DEFAULT = {
        scanTimeout: 2E2, /* 扫描超时时间(扫描枪两次按键最大时间间隔, 超时后清空当前扫描内容) */
        el: window.document, /* 监控元素 */
        success: $.loop, /* 扫描成功回调 */
        error: $.loop           /* 扫描失败回调 */
    };

    function BarcodeScanner(config) {
        var me = this;

        if (!(me instanceof BarcodeScanner)) {
            return new BarcodeScanner(config);
        }

        me.config = $.extend({}, DEFAULT, config || {});
        me._lastInputTime = new Date().getTime();
        me._barcode = '';
    }

    $.extend(true, BarcodeScanner.prototype, {
        resume: function () {
            var me = this;

            me.stop();
            $(me.config.el).on('keypress', function (e) {
                var now = new Date().getTime(),
                    code = e.keyCode,
                    ch = String.fromCharCode(code),
                    activeEl = document.activeElement,
                    timeout = false;

                timeout = now - me._lastInputTime > me.config.scanTimeout;
                me._lastInputTime = now;

                if (activeEl && me.config.el != activeEl && ('INPUT' == activeEl.nodeName || 'TEXTAREA' == activeEl.nodeName || 'SELECT' == activeEl.nodeName)) {
                    return;
                }

                // console.log(String.fromCharCode(e.charCode));
                // 如果超时, 清空当前扫描内容
                me._barcode = timeout ? ch : me._barcode + ch;

                // 如果回车 (扫描枪扫描结束)
                if (13 == code) {
                    if ('' === me._barcode) {
                        return;
                    }

                    me.config.success(me._barcode);
                    me._barcode = '';
                    e.stopPropagation();
                    return false;
                }
            });
        },
        stop: function () {
            $(this.config.el).off('keypress');
        }
    });

    exports.BarcodeScanner = BarcodeScanner;
})(jQuery, window);

